#!/usr/bin/env python
# encoding=utf-8
import json
from scpy.logger import get_logger
import traceback
import copy
import chardet
import re
from scpy.xawesome_time import parse_time
import traceback

import sd_trans_dict as TR
import sd_template_dict as TE

logger = get_logger(__file__)


def check_dict_void(test_dict):
    """
    check values in a dict are all void
    :param test_dict: a dict
    :return: `True`: all void, `False`: not all void
    """
    if not isinstance(test_dict, dict):
        raise Exception("input dict is not a dict")

    if not test_dict:
        return True

    for v in test_dict.values():
        if v == "":
            continue
        else:
            return False
            # break
    return True


def money_notclean(money):
    money = money.replace(",", "")
    number = re.findall('-*\d+', money)
    number = float('.'.join(number)) if number else float(0)
    return number


def trans_time(a_dict, clean_time_list):
    res_dict = copy.deepcopy(a_dict)
    if not isinstance(a_dict, dict):
        raise ValueError("input is not a dict")
    for k, v in a_dict.items():
        if k in clean_time_list and v:
            res_dict[k] = parse_time(v)
    return res_dict


def trans_money(a_dict, clean_money_list):
    res_dict = copy.deepcopy(a_dict)
    if not isinstance(a_dict, dict):
        raise ValueError("input is not a dict")
    for k, v in a_dict.items():
        if k in clean_money_list and v:
            if isinstance(v, float) or '不公示' in v or '无' in v:
                continue
            elif isinstance(v, int):
                v = float(v)
            elif isinstance(v, basestring):
                v = money_notclean(v)
            else:
                raise ValueError("")

            res_dict[k] = v
    return res_dict


def transform_dict(template_dict, trans_dict, a_dict):
    result_dict = copy.deepcopy(template_dict)
    for k, v in result_dict.items():
        if k not in trans_dict:
            raise ValueError("trans_dict and template_dict is not match")
        trans_v = trans_dict[k]
        if trans_v:
            a_k = trans_v
            if a_k not in a_dict:
                result_dict[k] = ''
            else:
                try:
                    if a_dict.get(a_k, None) is None:
                        result_dict[k] = ""
                    else:
                        result_dict[k] = a_dict[a_k]
                except Exception, e:
                    traceback.print_exc()
                    logger.error("检查字段！")
                    print k, a_k, '\n'
                    print 'template_dict:\n', template_dict
                    print 'trans_dict:\n', trans_dict
                    print 'a_dict:\n', a_dict
                    # import pdb
                    # pdb.set_trace()
        else:
            # has no key in a_dict
            pass
    return result_dict


def clean_all(test):
    """
    仅使用于清洗的字段所在的最小对象为字典以及，该字典的value全部basestring或者float或者int
    :param test:
    :return:
    """
    if isinstance(test, dict):
        for k, v in test.items():
            try:
                if isinstance(v, basestring) or isinstance(v, float) or isinstance(v, int):
                    if k in TR.time_list and v:
                        test[k] = parse_time(v)

                    elif k in TR.money_list:
                        if isinstance(v, int):
                            test[k] = float(v)
                        elif isinstance(v, float):
                            test[k] = v
                        elif isinstance(v, basestring):
                            if '不公示' in v or '无' in v:
                                test[k] = v
                            else:
                                test[k] = money_notclean(v)
                        else:
                            test[k] = v
                    else:
                        test[k] = v
                else:
                    test[k] = clean_all(copy.deepcopy(v))
            except Exception, e:
                traceback.print_exc(e)
                print k, v

    elif isinstance(test, list):
        continue_list = []
        for item in test:
            temp_item = clean_all(copy.deepcopy(item))
            continue_list.append(temp_item)

        test = continue_list
    else:
        return test

    return test


def format_input(a_dict):
    if isinstance(a_dict, basestring):
        try:
            a_dict = json.loads(a_dict)
            json.dumps(a_dict, indent=4, ensure_ascii=False)
        except Exception, e:
            traceback.print_exc()
            logger.exception(e)
            raise ValueError("You input must be a dict or string can be loaded json!")
    elif not isinstance(a_dict, dict):
        raise ValueError("You input must be a dict or string can be loaded json!")
    return a_dict
